import React, { Fragment } from 'react'
import { View, StyleSheet, Text, ScrollView, Image } from 'react-native'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CustomButton from 'src/components/button/CustomButton'
import { getAreaListByCityName, cityPositioning } from 'src/utils/RequestAPI'
import { getCurrentPosition } from 'src/store/actions/landmark'
import { isLegalCity } from 'src/utils/ConfigUtil'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'

class BaseJobArea extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      workPlaceDataSource: [],
      jobPlace: this.props.cityName,
      workPlace: []
    }
  }

  componentWillMount () {
    this.getAreaListByCityNameRequest()
  }

  getAreaListByCityNameRequest = (cityName) => {
    if (!cityName) {
      cityName = this.state.jobPlace
    }
    ShowLoading()
    getAreaListByCityName({ params: { cityName } }).then(
      ({ data: workPlaceDataSource }) => {
        this.setState({ workPlaceDataSource })
      }
    ).finally(() => {
      DismissLoading()
    })
  }

  childRender = () => {
    const { jobPlace } = this.state
    return (
      <Fragment>
        <ScrollView style={styles.container} >
          <View style={[styles.jobNatureView]}>
            <View style={styles.jobNatureTitleView}>
              <Text style={styles.jobNatureTitle}>工作区域</Text>
              {this.renderStepView()}
            </View>
            <Text style={styles.jobNatureTitleStatement}>
              *选择你想工作的区域吧，可选3个哦！
            </Text>
            {this._renderSelectedView()}
            <View style={styles.jobAreaLocationView}>
              <CustomButton style={styles.locationLabelView} onPress={this.selectCityList}>
                <Text style={styles.locationLabel}>{jobPlace}</Text>
                <Image
                  style={styles.locationLabelImg}
                  source={require('@/imgC/userinfo/location-select.png')}
                />
              </CustomButton>
              <CustomButton onPress={this.getPositionClick}>
                <Image
                  style={styles.locationImg}
                  source={require('@/imgC/userinfo/location.png')}
                />
              </CustomButton>

            </View>
            <View style={styles.jobAreaAreaView}>{this._renderAreaItem()}</View>
          </View>
        </ScrollView>
        {this.renderBottomBtn()}
      </Fragment>
    )
  }

  renderStepView () {}

  renderBottomBtn () {}

  _renderSelectedView = () => {
    const { workPlace } = this.state
    return (
      <View style={styles.jobExpectedSelectedView}>
        {workPlace && workPlace.length > 0 && workPlace.map((item, index) =>
          <View
            key={index}
            style={[
              styles.selectedItemView,
              index > 0 && {
                marginLeft: ScaleS(28)
              }
            ]}
          >
            <Text style={styles.selectedItemLabel}>{item}</Text>
            <CustomButton
              style={styles.closeBtnView}
              params={item}
              onPress={this._clearSelectItem}
            >
              <Image
                style={styles.closeBtn}
                source={require('@/imgC/userinfo/close-black.png')}
              />
            </CustomButton>
          </View>

        )}
      </View>
    )
  }

  _clearSelectItem = (item) => {
    const { workPlace } = this.state
    this.setState({
      workPlace: workPlace.filter(e => e !== item)
    })
  }

  /**
   * 渲染工作区域每一条
   * @private
   */
  _renderAreaItem = () => {
    const { workPlaceDataSource, workPlace } = this.state
    return workPlaceDataSource.map((item, index) => {
      const isSelected = workPlace.includes(item)
      return (
        <View key={index}>
          <CustomButton
            params={item}
            onPress={this._areaItemClick}
            style={[
              styles.areaItemView,
              {
                borderColor: isSelected ? '#FFC200' : '#CCCCCC',
                marginTop: index < 3 ? 0 : ScaleS(20),
                marginLeft: index % 3 === 0 ? 0 : ScaleS(20)
              }
            ]}
          >
            <Text
              style={[
                styles.areaItemText,
                {
                  color: isSelected ? '#FFC200' : '#666666'
                }
              ]}
            >
              {item}
            </Text>
          </CustomButton>
        </View>
      )
    })
  }

  _areaItemClick = item => {
    const { workPlace } = this.state
    if (workPlace.includes(item)) {
      this.setState({
        workPlace: workPlace.filter(e => e !== item)
      })
    } else {
      if (workPlace.length >= 3) {
        // toast提示
      } else {
        this.setState({
          workPlace: [...workPlace, item]
        })
      }
    }
  }

  getPosition = () => {
    return new Promise((resolve, reject) => {
      getCurrentPosition().then(({ lat, lng }) => {
        return cityPositioning({ query: { lat, lng } })
      })
        .then(({ data: jobPlace }) => {
          resolve({
            jobPlace
          })
        })
    })
  }

  getPositionClick = () => {
    this.getPosition().then(({
      jobPlace
    }) => {
      if (isLegalCity(jobPlace)) {
        this.jobPlaceChanged(jobPlace)
      } else {
        CommonToast(`地址不支持${jobPlace}`)
      }
    })
  }

  selectCityList = () => {
    const callback = jobPlace => {
      this.jobPlaceChanged(jobPlace)
    }
    this.props.navigation.navigate('CommonListCity', {
      cityName: this.state.jobPlace,
      callback
    })
  }

  jobPlaceChanged = (jobPlace) => {
    if (jobPlace !== this.state.jobPlace) {
      this.setState({
        jobPlace,
        workPlace: []
      })
      this.getAreaListByCityNameRequest(jobPlace)
    }
  }
}

export default BaseJobArea

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginBottom: ScaleS(105)
  },
  jobNatureView: {
    width: ScaleS(363),
    paddingHorizontal: ScaleS(20),
    marginHorizontal: ScaleS(6),
    backgroundColor: 'white',
    borderRadius: ScaleS(12),
    marginTop: ScaleS(30)
  },
  jobNatureTitleView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  jobNatureTitle: {
    color: '#444444',
    fontSize: ScaleT(27),
    fontWeight: '500',
    flex: 1
  },
  jobNatureIndexView: {
    flexDirection: 'row',
    alignItems: 'flex-end'
  },
  jobNatureIndex: {
    color: '#999999',
    fontSize: ScaleT(20),
    fontWeight: '500'
  },
  jobNatureTotal: {
    color: '#999999',
    fontSize: ScaleT(16),
    fontWeight: '500'
  },
  jobNatureTitleStatement: {
    color: '#FFC200',
    fontSize: ScaleT(14),
    fontWeight: '400',
    marginTop: ScaleS(18)
  },
  jobExpectedSelectedView: {
    flexDirection: 'row',
    alignItems: 'center',
    height: ScaleS(83)
  },
  selectContentView: {
    height: ScaleS(325),
    flexDirection: 'row',
    width: '100%'
  },
  selectedItemView: {
    width: ScaleS(75),
    height: ScaleS(34),
    borderWidth: ScaleS(1),
    borderStyle: 'solid',
    borderColor: '#FFC200',
    borderRadius: ScaleS(4),
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative'
  },
  selectedItemLabel: {
    color: '#FFC200',
    fontSize: ScaleT(11),
    fontWeight: '400'
  },
  closeBtnView: {
    width: ScaleS(15),
    height: ScaleS(15),
    position: 'absolute',
    top: ScaleS(-7),
    right: ScaleS(-7)
  },
  closeBtn: {
    width: ScaleS(15),
    height: ScaleS(15)
  },
  jobAreaLocationView: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: ScaleS(10)
  },
  locationLabelView: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    flex: 1
  },
  locationLabel: {
    color: '#000000',
    fontSize: ScaleT(32),
    fontWeight: '600'
  },
  locationLabelImg: {
    width: ScaleS(11),
    height: ScaleS(19),
    marginLeft: ScaleS(10),
    resizeMode: 'contain'
  },
  locationImg: {
    width: ScaleS(18),
    height: ScaleS(22),
    resizeMode: 'contain'
  },
  jobAreaAreaView: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: ScaleS(30)
  },
  areaItemView: {
    width: ScaleS(94),
    height: ScaleS(42),
    borderRadius: ScaleS(5),
    borderStyle: 'solid',
    borderWidth: ScaleS(1),
    justifyContent: 'center',
    alignItems: 'center'
  },
  areaItemText: {
    fontSize: ScaleT(14),
    fontWeight: '400'
  },
  jobNatureNextStepView: {
    width: ScaleS(297),
    height: ScaleS(50),
    backgroundColor: '#000000',
    borderRadius: ScaleS(5),
    marginTop: ScaleS(122),
    marginBottom: ScaleS(26),
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: ScaleS(13)
  },
  jobNatureNextStep: {
    color: '#ffffff',
    fontSize: ScaleT(15),
    fontWeight: '600'
  }
})
